<?php
namespace control;
/*
*外调车辆类
*/

class logisticsTransferCarClass extends adIndexClass
{
    private const page = 'logisticsTransferCar';
    private const table = 'logistics_transfer_car';
    private const title = '外调车辆';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'unit_name'          => [
                        'name'  => '单位名称',
                        'width' => 200,
                    ],
                    'name' => [
                        'name'  => "驾驶员",
                        'width' => 150,
                    ],
                    'idCard'  => [
                        'name'  => "身份证号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'contactTel'  => [
                        'name'  => "联系电话",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'carNo'  => [
                        'name'  => "车牌号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'brand'         => [
                        'name'  => '车辆品牌',
                        'width' => 100,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'endDate'          => [
                        'name'  => '驾驶证有效结束日期',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'driving_end_date'          => [
                        'name'  => '行驶证有效结束日期',
                        'width' => 180,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单位名称" => text(array("name" => "unit_name")),
                    "驾驶员"   => text(array("name" => "name")),
                    "身份证号"   => text(array("name" => "idCard")),
                ],
                [
                    "联系电话"   => text(array("name" => "contactTel")),
                    "车牌号"   => text(array("name" => "carNo")),
                    "驾驶证有效结束日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "unit_name" => $this->post('unit_name'),//单位名称
            "name" => $this->post('name'),//驾驶员
            "idCard" => $this->post('idCard'),//身份证号
            "contactTel" => $this->post('contactTel'),//联系电话
            "carNo" => $this->post('carNo'),//车牌号
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'),'date','endDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'endDate',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'carNo':
                        $row[] = $array['shortName'] . $array['carNo'];
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditForm,supplierImgSingleForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        $licenseUrl = query('file',"targetId = '$id' and target ='身份证正面'");
        $licenseUrl2 = query('file',"targetId = '$id' and target ='身份证反面'");
        $licenseUrl3 = query('file',"targetId = '$id' and target ='驾驶证'");
        $licenseUrl4 = query('file',"targetId = '$id' and target ='行驶证'");
        $licenseUrl5 = query('file',"targetId = '$id' and target ='车辆图片'");
        $photo = array(
            array("title" => "身份证正面", 'type' => '身份证正面', 'fileId'=>$licenseUrl['id'] ?? '',"url" => $licenseUrl['src'] ?? '','id'=>$id),
            array("title" => "身份证反面", 'type' => '身份证反面', 'fileId'=>$licenseUrl2['id'] ?? '',"url" => $licenseUrl2['src'] ?? '','id'=>$id),
            array("title" => "驾驶证", 'type' => '驾驶证', 'fileId'=>$licenseUrl3['id'] ?? '',"url" => $licenseUrl3['src'] ?? '','id'=>$id),
            array("title" => "行驶证", 'type' => '行驶证','fileId'=>$licenseUrl4['id'] ?? '', "url" => $licenseUrl4['src'] ?? '','id'=>$id),
            array("title" => "车辆图片", 'type' => '车辆图片','fileId'=>$licenseUrl5['id'] ?? '', "url" => $licenseUrl5['src'] ?? '','id'=>$id),
        );
        $talentObj = new talentPoolClass();
        //表单
        $data['button'] = $this->tableShowButton($button);
        $data['html'] = $this->pageEdit([
            "table" => [
                '基本信息' => [
                    [
                        must . "姓名：" =>  text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                        must . "身份证号：" => text(["name" => "idCard", 'class' => 'text', "value" => $info['idCard']]),
                        must . "单位名称：" =>  "<div class='full'>".selectMultiple(["name" => "unit_select", 'title' => '选择已有单位', 'table' => "logistics_transfer_car", 'where' => " coid = '" . self::$coid . "' group by unit_name ", 'field' => 'unit_name', 'sqlId' => 'unit_name', 'sqlField' => 'unit_name', 'change' => 'selectGetText', "value" => $info['unit_name']])."</div>".
                            text(["name" => "unit_name", "value" => $info['unit_name']]),
                    ],
                    [
                        must . "联系电话：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                        "联系地址：" => text(["name" => "address", 'class' => 'text', "value" => $info['address']]),
                        must . "车牌号：" => select(["name" => "shortName", 'option' => explode('，', para('shortNameOption')), "value" => $info['shortName']]) .
                            text(["name" => "carNo", "value" => $info['carNo']]),
                    ],
                    [
                        "车牌品牌：" => text(["name" => "brand", 'class' => 'text', "value" => $info['brand']]),
                        "规格型号：" => text(["name" => "model", 'class' => 'text', "value" => $info['model']]),
                        "车辆类型：" => select(["name" => "carType", 'title' => '类型', 'option' => explode('，', para('carType')), "value" => $info['carType']]),
                        "核定载人数：" => text(["name" => "maxPeople", 'class' => 'text', "value" => $info['maxPeople']]),
                    ],
                    [
                        "核定载重：" => text(["name" => "maxWeight", 'unit' => 'kg', 'class' => 'text', "value" => $info['maxWeight']]),
                        "驾驶证号：" => text(["name" => "licenseNo", 'class' => 'text', "value" => $info['licenseNo']]),
                        "驾驶证有效结束日期：" => text(["name" => "endDate",'laydate' => [],"value" => $info['endDate']]),
                        "行驶证号：" => text(["name" => "driving_license", 'class' => 'text', "value" => $info['driving_license']]),
                    ],
                    [
                        "行驶证有效结束日期：" => text(["name" => "driving_end_date",'laydate' => [],"value" => $info['driving_end_date']]),
                        "收款账户名称：" => text(["name" => "account_name", 'class' => 'text', "value" => $info['account_name']]),
                        "银行账号：" => text(["name" => "bankAccount", 'class' => 'text', "value" => $info['bankAccount']]),
                        "开户行：" => text(["name" => "bankName", 'class' => 'text', "value" => $info['bankName']]),
                    ],
                    [
                        "备注：" => textarea(["name" => "text",  'class' => 'textarea', "value" => $info['text']]),
                    ],
                ],
                '证件' => [
                    [$talentObj->photo($photo)],
                ]
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]). "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco')\"></div>",
        ]);

        $version = version;
        $data['html'] .= <<<efo
<script>
    /*将下拉菜单赋值到下一个输入框*/
    function selectGetText(obj){
        $("[name='unit_name']").val(obj.value);
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getAccount',{unit_name:obj.value},function(res) {
            $("[name='account_name']").text(res.account_name)
            $("[name='bankAccount']").html(res.bankAccount)
            $("[name='bankName']").html(res.bankName)
       },'json')
    }
    function delSingleIco(id){
      $.post(root+'control/adIndex.html?cla=talentPool&fun=delIco',{id:id},function(res) {
            if (res.warn ==2){
                $("[data-type='"+res.data.type+"']").attr('src',root+'img/images/emptyImg.jpg')
                 $("[data-type='"+res.data.type+"']").closest('li').find(".edit-ico").attr('src',root+'img/control/clickEdit.svg?v=$version');
                 $("[data-type='"+res.data.type+"']").closest('li').find(".edit-ico").attr('onclick',"clickUpload('"+res.data.type+"','"+res.data.id+"')")
            }else{
                msg(res.warn,'error')
            }
       },'json')
     }
</script>
efo;

        //返回
        return $this->tab($data);
    }
    /**
     *获取单位银行账户
     */
    function getAccount()
    {
        $logistics_transfer_car = query("logistics_transfer_car"," unit_name = '".$this->post('unit_name')."' ");
        $json = [
            'account_name'=>$logistics_transfer_car['account_name'],
            'bankName'=>$logistics_transfer_car['bankName'],
            'bankAccount'=>$logistics_transfer_car['bankAccount'],
        ];
        return json_encode($json, 320);
    }
    /**
     *上传图片
     */
    function uploadIco()
    {
        $type = $this->post('type');
        $result = $this->saveFile($_FILES['imgFile'], self::page, explode(',', para('fileFormat')));
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        }elseif (empty($type)) {
            $json['warn'] = '未找到类型';
        }elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } elseif (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $field = array(
                'src'=>$result['src'],
                'name'=>$result['fileName'],
                'size'=>$result['size'],
                'format'=>$result['suffix'],
            );
            $file = query('file',"targetId = '$id' and target = '$type'");
            if (empty($file['id'])){
                $field = array_merge($field,[
                    'id'=>self::getId(),
                    'stid'=>self::$stid,
                    'target'=>$type,
                    'targetId'=>$id,
                ]);
                $json['warn'] =static::insert(array(
                    'table'=>'file',
                    'field'=>$field
                ));
                $fileId = $field['id'];
            }else{
                $json['warn'] =static::update(array(
                    'table'=>'file',
                    'field'=>$field,
                    'where'=>"id = '$file[id]'"
                ));
                $fileId = $file['id'];
            }
            //添加日志
            if (in_array($json['warn'] ,['新增成功','更新成功'])) {
                fileDelete($file['src']);//删除之前的图片
                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
                $json['data']['fileHtml'] = hidden(array('name'=>"imgId[]",'value'=>$fileId));
            }
        }
        return json_encode($json, 320);
    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $fileId = $this->post('imgId');
        $field = [
            'unit_name' => $this->post('unit_name'),
            'name' => $this->post('name'),
            'idCard' => $this->post('idCard'),
            'contactTel' => $this->post('contactTel'),
            'address' => $this->post('address'),
            'shortName' => $this->post('shortName'),
            'carNo' => $this->post('carNo'),
            'brand' => $this->post('brand'),
            'model' => $this->post('model'),
            'carType' => $this->post('carType'),
            'maxPeople' => $this->post('maxPeople'),
            'maxWeight' => $this->post('maxWeight'),
            'licenseNo' => $this->post('licenseNo'),
            'endDate' => $this->post('endDate'),
            'driving_license' => $this->post('driving_license'),
            'driving_end_date' => $this->post('driving_end_date'),
            'account_name' => $this->post('account_name'),
            'bankAccount' => $this->post('bankAccount'),
            'bankName' => $this->post('bankName'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'unit_name' => '单位名称',
            'name' => '姓名',
            'idCard' => '身份证号',
            'contactTel' => '联系电话',
            'shortName' => '车牌号',
            'carNo' => '车牌号',
        ];
        $rules = [
            'unit_name' => 'required',
            'name' => 'required',
            'idCard' => 'required|id_card',
            'contactTel' => 'required|tel',
            'shortName' => 'required',
            'carNo' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => "logistics_transfer_car", 'where' => " and coid = '".self::$coid."' and carNo ='$field[carNo]' and shortName = '$field[shortName]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此外调车牌号';
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'WD',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //更新文件
                if (is_array($fileId) && !static::isNull($fileId)) {
                    update(['table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileId) . "')"]);
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];

            }
            $licenseUrl = query('file',"targetId = '$info[id]' and target ='身份证正面'");
            $licenseUrl2 = query('file',"targetId = '$info[id]' and target ='身份证反面'");
            $licenseUrl3 = query('file',"targetId = '$info[id]' and target ='驾驶证'");
            $licenseUrl4 = query('file',"targetId = '$info[id]' and target ='行驶证'");
            $licenseUrl5 = query('file',"targetId = '$info[id]' and target ='车辆图片'");
            $photo = array(
                array("title" => "身份证正面", 'type' => '身份证正面', 'cla'=>self::page,"url" => $licenseUrl['src']),
                array("title" => "身份证反面", 'type' => '身份证反面', 'cla'=>self::page,"url" => $licenseUrl2['src']),
                array("title" => "驾驶证", 'type' => '驾驶证', 'cla'=>self::page,"url" => $licenseUrl3['src']),
                array("title" => "行驶证", 'type' => '行驶证','cla'=>self::page, "url" => $licenseUrl4['src']),
                array("title" => "车辆图片", 'type' => '车辆图片','cla'=>self::page, "url" => $licenseUrl5['src']),
            );
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "单位名称" => $info['unit_name'],
                        "姓名" => $info['name'],
                        "身份证号" => $info['idCard'],
                        "联系电话" =>  $info['contactTel'],
                    ),
                    array(
                        "联系地址" => $info['address'],
                        "车牌号" => $info['shortName'].$info['carNo'],
                        "车辆品牌" => $info['brand'],
                        "规格型号" => $info['model'],
                    ),
                    array(
                        "车辆类型" => $info['carType'],
                        "核定载人数（人）" => $info['maxPeople'],
                        "核定载重（kg）" => $info['maxWeight'],
                        "驾驶证号" => $info['licenseNo'],
                    ),
                    array(
                        "驾驶证有效结束日期" => $info['endDate'],
                        "行驶证号" => $info['driving_license'],
                        "行驶证有效结束日期" => $info['driving_start_date'],
                        "收款账号名称" => $info['account_name'],
                    ),
                    array(
                        "银行账户" => $info['bankAccount'],
                        "开户行" => $info['bankName'],
                        "备注" =>$info['text'],
                    ),
                ),
                '系统信息' => array(
                    array(
                        "外调车辆编号" => $info['orderNo'],
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                    ),
                ),
                "证件" => [
                    [
                        supplierClass::singlePhoto($photo)
                    ]
                ]
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;

                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

